package com.tarena.demo.luban.all.main.service.impl;

import com.alibaba.csp.sentinel.Entry;
import com.alibaba.csp.sentinel.SphU;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.tarena.demo.luban.all.main.mapper.OrderMapper;
import com.tarena.demo.luban.all.main.service.OrderService;
import com.tarena.demo.luban.cart.api.CartApi;
import com.tarena.demo.luban.protocol.cart.param.CartDeleteParam;
import com.tarena.demo.luban.protocol.order.dos.OrderDO;
import com.tarena.demo.luban.protocol.order.param.OrderAddParam;
import com.tarena.demo.luban.protocol.stock.param.StockReduceCountParam;
import com.tarena.demo.luban.stock.api.StockApi;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class OrderServiceImpl implements OrderService {
//    @Autowired
//    private CartService cartService;
//    @Autowired
//    private StockService stockService;

    @Autowired(required = false)
    private CartApi cartApi;
    @Autowired(required = false)
    private StockApi stockApi;
    // required = true: 容器中未找到对象,not found
    // required = false:容器中未找到对象,不装配,null-NPE

    @Autowired
    private OrderMapper orderMapper;
    @Override public void addOrder(OrderAddParam param) {

        // 查询订单orderSn是否存在订单,不存在则执行后续代码
        long count= orderMapper.countOrderByOrderSn(param.getOrderSn());
        if(count>0){
            //抛异常/结束方法调用
            return;
        }

        // 减库存
        StockReduceCountParam stockReduceCountParam=new StockReduceCountParam();
        stockReduceCountParam.setReduceCount(param.getCount());
        stockReduceCountParam.setProductCode(param.getProductCode());
        stockReduceCountParam.setOrderSn(param.getOrderSn());
//        stockService.reduceCommodityCount(stockReduceCountParam);
        stockApi.reduceCommodityCount(stockReduceCountParam);
        //增订单
        OrderDO orderDO=new OrderDO();
        BeanUtils.copyProperties(param,orderDO);
        orderMapper.insertOrder(orderDO);

        Entry entry = null;
        try {
            entry = SphU.entry("delete-cart");
            //删除购物车
            //Thread.sleep(70);
            CartDeleteParam cartDeleteParam=new CartDeleteParam();
            cartDeleteParam.setUserId(param.getUserId());
            cartDeleteParam.setProductCode(param.getProductCode());
//        cartService.deleteCart(cartDeleteParam);
            cartApi.deleteCart(cartDeleteParam);
        } catch (BlockException e) {
            // 人工检查: 哪个订单-哪个用户-哪个商品
            System.out.println("记录当前订单信息");
        }finally {
            if(entry!=null){
                entry.exit();
            }
        }
    }
}
